package com.kgc.crowd.distributioncrowdwebui.controller;

import com.kgc.crowd.distributioncrowdcommon.api.MemberManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.api.ProjectManagerRemoteService;
import com.kgc.crowd.distributioncrowdcommon.pojo.MemberLaunchInfoPO;
import com.kgc.crowd.distributioncrowdcommon.pojo.ResultEntity;
import com.kgc.crowd.distributioncrowdcommon.pojo.TypePO;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdConstant;
import com.kgc.crowd.distributioncrowdcommon.util.CrowdUtils;
import com.kgc.crowd.distributioncrowdcommon.util.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/project/manager")
public class ProjectController {
    @Value("${endpoint}")
    public String endpoint;
    @Value("${accessKeyId}")
    public String accessKeyId;
    @Value("${accessKeySecret}")
    public String accessKeySecret;
    @Value("${headPictureFolderName}")
    public String headPictureFolderName;
    @Value("${bucketName}")
    public String bucketName;
    @Value("${domain}")
    public String domain;
    @Value("${ossProjectParentFolder}")
    public String ossProjectParentFolder;


    @Resource
    ProjectManagerRemoteService projectManagerRemoteService;

    @Resource
    MemberManagerRemoteService memberManagerRemoteService;

    @RequestMapping("/start")
    public String start(){
        return "start";
    }

    @RequestMapping("/agree/protocol")
    public String protocol(Model model,HttpSession session){
        //获取登录状态
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj == null) {
            return "redirect:/to/login.html";
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO) obj;
        String token=memberSignSuccessVO.getToken();
        //加载分类信息
        ResultEntity<List<TypePO>> resultEntity=projectManagerRemoteService.selectAllType();
        model.addAttribute(CrowdConstant.ATTR_NAME_TYPEPO_LIST,resultEntity.getData());
        //加载标签信息
        ResultEntity<List<TagVO>> tagList=projectManagerRemoteService.selectAllTag();
        model.addAttribute(CrowdConstant.ATTR_NAME_TAGPO_LIST,tagList.getData());
        //回显发起人信息

        //初始化projectVO
        ResultEntity<ProjectVO> projectVOResultEntity=projectManagerRemoteService.initCreation(token);
        if (projectVOResultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,projectVOResultEntity.getMessage());
            return  "redirect:/project/manager/start";
        }
        //projectVO存入session
        session.setAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT,projectVOResultEntity.getData());
        return "redirect:/project/manager/project/to/create/project/page";
    }


    @RequestMapping("/upload/head/picture")
    @ResponseBody
    public ResultEntity<String> uploagHeadPicture(MultipartFile headerPicture,HttpSession session) throws IOException{
        Object obj=session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if (obj==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        MemberSignSuccessVO memberSignSuccessVO=(MemberSignSuccessVO) obj;
        String memberSignToken=memberSignSuccessVO.getToken();
        Object obj2=session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        if (obj2==null){
            return ResultEntity.failed(CrowdConstant.ATTR_NAME_NO_INITED_PROJECT);
        }
        ProjectVO projectVO=(ProjectVO) obj2;
        String projectTempToken=projectVO.getProjectTempToken();

        if (headerPicture==null){
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }
        String originalFilename=headerPicture.getOriginalFilename();
        String fileName= UploadUtil.generateFileName(originalFilename);
        InputStream inputStream=headerPicture.getInputStream();
        UploadUtil.uploagSingleFile(endpoint,accessKeyId,accessKeySecret, fileName, headPictureFolderName, bucketName,inputStream);

        String headPicturePath=domain+"/"+headPictureFolderName+"/"+fileName;

        return projectManagerRemoteService.saveHeadPicturePath(memberSignToken,projectTempToken,headPicturePath);
    }

    @ResponseBody
    @RequestMapping("/upload/detail/picture")
    public ResultEntity<String> uploadDetailPicture(
            HttpSession session,
            @RequestParam("detailPicture") List<MultipartFile> detailPictureList
    ) throws IOException {

        // 登录检查
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        if(signVO == null) {

            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }

        // 遍历用户上传的文件
        if(!CrowdUtils.collectionEffectiveCheck(detailPictureList)) {
            return ResultEntity.failed(CrowdConstant.MESSAGE_NO_FILE);
        }

        List<String> detailPicturePathList = new ArrayList<>();

        for (MultipartFile detailPicture : detailPictureList) {
            boolean empty = detailPicture.isEmpty();
            if(empty) {
                continue ;
            }
            InputStream inputStream = detailPicture.getInputStream();

            String originalFileName = detailPicture.getOriginalFilename();

            String fileName = UploadUtil.generateFileName(originalFileName);

            String folderName = UploadUtil.generateFolderNameByDate(ossProjectParentFolder);

            UploadUtil.uploagSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, folderName, bucketName, inputStream);

            String detailPicturePath = domain + "/" + folderName + "/" + fileName;

            detailPicturePathList.add(detailPicturePath);
        }

        // 获取保存头图所需要的相关信息
        String memberSignToken = signVO.getToken();

        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);

        String projectTempToken = projectVO.getProjectTempToken();

        return projectManagerRemoteService.saveDetailPicturePathList(memberSignToken, projectTempToken, detailPicturePathList);

    }

    @RequestMapping("/project/to/create/project/page")
    public String toCreateProjectPage(HttpSession session, Model model) {

        // 1.获取当前登录的用户
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        // 2.检查signVO为null
        if(signVO == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "member-login";
        }
        // 3.获取token数据
        String token = signVO.getToken();
        // 4.根据token查询MemberLaunchInfo信息
        ResultEntity<MemberLaunchInfoPO> resultEntity = memberManagerRemoteService.retrieveMemberLaunchInfoByMemberToken(token);
        // 5.检查结果
        String result = resultEntity.getResult();
        if(ResultEntity.FAILED.equals(result)) {
            throw new RuntimeException(resultEntity.getMessage());
        }
        // 6.获取查询结果
        MemberLaunchInfoPO memberLaunchInfoPO = resultEntity.getData();
        // 7.存入模型
        model.addAttribute("memberLaunchInfoPO", memberLaunchInfoPO);
        //8.显示所有分类
        ResultEntity<List<TypePO>> typeListResultEntity = projectManagerRemoteService.selectAllType();
        model.addAttribute("typeList",typeListResultEntity.getData());
        //9.获取所有标签
        ResultEntity<List<TagVO>> tagListResultEntity = projectManagerRemoteService.selectAllTag();
        model.addAttribute("tagList",tagListResultEntity.getData());

        return "start-step-1";
    }

    @ResponseBody
    @RequestMapping("/save/project/information")
    public ResultEntity<String> saveProjectInformation(ProjectVO projectVO,HttpSession session){
        // 登录检查
        MemberSignSuccessVO signVO = (MemberSignSuccessVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        if(signVO == null) {

            return ResultEntity.failed(CrowdConstant.MESSAGE_ACCESS_DENIED);
        }
        projectVO.setMemberSignToken(signVO.getToken());
        ProjectVO project = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        projectVO.setProjectTempToken(project.getProjectTempToken());
        ResultEntity<String> projectResultEntity = projectManagerRemoteService.saveProjectInformation(projectVO);
        return projectResultEntity;
    }

    @RequestMapping("/to/project/return")
    public String toProjectReturn(){
        return "start-step-2";
    }

    @RequestMapping("/save/return/vo")
    public String saveReturnVO(ReturnVO returnVO, @RequestParam("describPic") MultipartFile describPic, HttpSession session, Model model) throws IOException {

        // 登录检查
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "member-login";
        }
        MemberSignSuccessVO signVO = (MemberSignSuccessVO)attribute;
        // 获取token数据
        String token = signVO.getToken();
        //獲取projectToken
        Object projectObject = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        ProjectVO projectVO= (ProjectVO) projectObject;
        String projectTempToken = projectVO.getProjectTempToken();

        //文件上传
        // 1.判断上传的文件是否为空
        if (describPic.isEmpty()) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_NO_FILE);
            return "";
        }
        // 2.获取文件原始文件名
        String originalFilename = describPic.getOriginalFilename();

        // 3.构造存储文件的目录名
        String folderName = ossProjectParentFolder + "/" + UploadUtil.generateDayFolderName();

        // 4.生成文件名
        String fileName = UploadUtil.generateFileName(originalFilename);

        // 5.获取上传文件提供的输入流
        InputStream inputStream = describPic.getInputStream();

        // 6.执行上传
        UploadUtil.uploagSingleFile(endpoint, accessKeyId, accessKeySecret, fileName, folderName, bucketName, inputStream);

        // 7.拼装上传文件后OSS平台上访问文件的路径
        String ossAccessPath = domain+"/"+folderName+"/"+fileName;

        returnVO.setMemberSignToken(token);
        returnVO.setProjectTempToken(projectTempToken);
        returnVO.setDescribPicPath(ossAccessPath);

        ResultEntity<String> resultEntity = projectManagerRemoteService.saveReturnVO(returnVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-2";
        }
        return "start-step-3";
    }

    @RequestMapping("/save/member/confirm/info/vo")
    public String saveMemberConfirmInfoVO(MemberConfirmInfoVO memberConfirmInfoVO, Model model, HttpSession session){
        // 登录检查
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        if(attribute == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_DENIED);
            return "member-login";
        }
        MemberSignSuccessVO signVO = (MemberSignSuccessVO)attribute;
        // 获取token数据
        String token = signVO.getToken();

        Object projectObject = session.getAttribute(CrowdConstant.ATTR_NAME_INITED_PROJECT);
        ProjectVO projectVO= (ProjectVO) projectObject;
        String projectTempToken = projectVO.getProjectTempToken();

        memberConfirmInfoVO.setMemberSignToken(token);
        memberConfirmInfoVO.setProjectTempToken(projectTempToken);

        ResultEntity<String> resultEntity = projectManagerRemoteService.saveMemberConfirmInfoVO(memberConfirmInfoVO);
        if (resultEntity.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-3";
        }
        //保存到数据库
        ResultEntity<String> resultEntity2 = projectManagerRemoteService.saveWholeProject(token, projectTempToken);
        if (resultEntity2.getResult().equals(ResultEntity.FAILED)){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,resultEntity.getMessage());
            return "start-step-3";
        }
        return "start-step-4";
    }

}
